"""
客户端
"""
import socket
import time
from threading import Thread

IP_PORT = ('124.221.242.12', 8000)  # 服务器IP+端口 端口必须开放

c = socket.socket()
c.connect(IP_PORT)


def msg_print():
    while True:
        result = c.recv(1024).decode('utf8')
        if f'{nickname}:' not in result:
            print()
            print(result, f'\n[{nickname}]:', sep='', end='')


def run():
    global nickname
    while True:
        # 1.输入昵称
        while True:
            nickname = input('请输入你的昵称:')
            if len(nickname) == 0:
                print('昵称不能为空！')
                continue
            c.send(nickname.encode('utf8'))
            nickname_result = c.recv(1024).decode('utf8')
            print(nickname_result)
            if nickname_result == f'昵称[{nickname}]加入聊天！':
                break

        # 提示
        print('欢迎来到聊天室！（输入q退出）')
        # 聊天页面
        Thread(target=msg_print).start()
        while True:
            msg = input(f'[{nickname}]:')

            if msg == 'q':
                print('退出老年聊天室!')
                exit(0)
            if len(msg) == 0:
                continue
            msg = ''.join([f'{nickname}:', msg])
            c.send(msg.encode('utf8'))
            print(msg)


if __name__ == '__main__':
    run()
